package xx.iverson.file_manager.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xx.iverson.file_manager.entity.CategoryLevel1;
import xx.iverson.file_manager.entity.CategoryLevel2;
import xx.iverson.file_manager.mapper.CategoryLevel1Mapper;
import xx.iverson.file_manager.mapper.CategoryLevel2Mapper;
import xx.iverson.file_manager.service.CategoryLevel1Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 86131
 */
@Service
public class CategoryLevel1ServiceImpl implements CategoryLevel1Service {

    @Autowired
    private CategoryLevel1Mapper categoryLevel1Mapper;

    @Autowired
    private CategoryLevel2Mapper categoryLevel2Mapper;

    @Override
    public List<CategoryLevel1> getAllLevel1Categories() {
        return categoryLevel1Mapper.selectAllLevel1Categories();
    }

    @Override
    public CategoryLevel1 getLevel1CategoryById(Integer id) {
        return categoryLevel1Mapper.selectLevel1CategoryById(id);
    }

    @Override
    @Transactional
    public boolean addLevel1Category(CategoryLevel1 category) {
        // 检查一级分类名称是否已存在
        CategoryLevel1 existingCategory = categoryLevel1Mapper.selectLevel1CategoryByName(category.getName());
        if (existingCategory != null) {
            return false;
        }

        int result = categoryLevel1Mapper.insertLevel1Category(category);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean updateLevel1Category(CategoryLevel1 category) {
        // 检查一级分类名称是否已被其他分类使用
        CategoryLevel1 existingCategory = categoryLevel1Mapper.selectLevel1CategoryByName(category.getName());
        if (existingCategory != null && !existingCategory.getId().equals(category.getId())) {
            return false;
        }

        int result = categoryLevel1Mapper.updateLevel1Category(category);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean deleteLevel1Category(Integer id) {
        // 检查一级分类下是否有二级分类
        List<CategoryLevel2> level2Categories = categoryLevel2Mapper.selectLevel2ByLevel1Id(id);
        if (level2Categories != null && !level2Categories.isEmpty()) {
            return false;
        }

        int result = categoryLevel1Mapper.deleteLevel1Category(id);
        return result > 0;
    }

    @Override
    public List<CategoryLevel1> getAllLevel1WithLevel2() {
        List<CategoryLevel1> level1Categories = categoryLevel1Mapper.selectAllLevel1WithLevel2();

        // 确保每个一级分类的level2Categories不为null
        if (level1Categories != null) {
            for (CategoryLevel1 level1 : level1Categories) {
                if (level1.getLevel2Categories() == null) {
                    level1.setLevel2Categories(new ArrayList<>());
                }
            }
        }

        return level1Categories;
    }
}